﻿using MediatR;
using RBAC.Common.Domains;
using RBAC.Common.Dto;
using RBAC.Common.infrastructures.interfaces;
using RBAC.Enum;

namespace RBAC.api.Application.commond.RBAC
{
    public class UserCreateHander : IRequestHandler<UserCreateCommand, Rulst>
    {

        private readonly IbaseRpository<User> _user;
        private readonly IbaseRpository<Role> _role;
        private readonly IbaseRpository<userRole> _userRole;
        public UserCreateHander(IbaseRpository<User> user, IbaseRpository<Role> role, IbaseRpository<userRole> userRole)
        {
            _user = user;
            _role = role;
            _userRole = userRole;   
        }


        /// <summary>
        /// 用户新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<Rulst> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
           
            var result= new Rulst() { Code=(int)Reult.success };


            var userst = new User()
            {
                Password=request.Gouser.Password,
                UserName=request.Gouser.UserName,
            };

            var list = _user.Add(userst);

            var Records = 0;
            var query=_user.Query().Where(x=>x.UserName==request.Gouser.UserName&&x.Password==request.Gouser.Password).FirstOrDefault();

            if(query!=null)
            {
                foreach (var item in request.Roleid) { 
                
                
                 var Rolest=new userRole() { 
                 Roleid=item,
                 Userid=query.Userid,
                 userRoleid=0,
                 };

                    Records = _userRole.Add(Rolest);
                }

              
            }

            if(list>0&&Records>0)
            {
                result.Code=(int)Reult.Addad;
            }


            return result;




        }


    }
}
